//
//  YDAddActionView.swift
//  weibo
//
//  Created by 孙亚东 on 16/6/29.
//  Copyright © 2016年 Sunyadong. All rights reserved.
//

import UIKit
import pop

//定义一个枚举

enum animationType: String  {

    case UP = "up"
    case DOWN = "down"


}

class YDAddActionView: UIView {
    
    
    //定义一个属性，将父类tableViewController传进来
    
    var viewController: UIViewController?
    
    // 创建一个数组，保存button
    lazy var btnArr: [YDAddButton] = [YDAddButton]()


    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI () {
        
        backgroundColor = UIColor.yellowColor()
    
        addSubview(bjImageView)
        
        
        //设置frame
        
        bjImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.snp_edges)
            
        }
        
        //添加button的方法
        
        addButton()
        
        showAnimation()
        

    }
    
    func addButton() {
        
        
        let childButtonW: CGFloat = 80
        let childButtonH: CGFloat = 110
        let margin: CGFloat = (screenWidth - 3.0 * childButtonW)/4.0

        
        //读取数组
        
        let str = NSBundle.mainBundle().pathForResource("compose", ofType: ".plist")
        
        let btnArray = NSArray(contentsOfFile: str!)!
        
        //九宫格遍历创建button
        
        for i in 0..<6  {
            
            //创建按钮
            
            let btn = YDAddButton()
            
            addSubview(btn)
            
            let dic = btnArray[i] as! [String : String]
            
            btn.setTitle(dic["title"], forState: .Normal)
            btn.setImage(UIImage(named: dic["icon"]!), forState: .Normal)
            
            
            //设置frame
            let rowNum = i / 3
            let colNum = i % 3
            
            var btnFrame = btn.frame
            
            btnFrame.origin.x = margin + (margin + childButtonW)*CGFloat(colNum)
            btnFrame.origin.y = (margin + childButtonH)*CGFloat(rowNum) + CGFloat(screenHeight)
            
            btnFrame.size = CGSizeMake(childButtonW, childButtonH)
            
            btn.frame = btnFrame
            
            //给btn添加点击方法
            
            btn.addTarget(self, action: "btnClick:", forControlEvents: .TouchUpInside)
            
            self.btnArr.append(btn)
 
        }

    
    }
    
    
    @objc private func btnClick (btn :YDAddButton) {
    
    

        
        //添加动画
        
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            //实现按钮的点击放大功能
            //遍历所有的按钮
            
            for button in self.btnArr {
                
                button.alpha = 0
            
            
                if button == btn {
                
                
                    button.transform = CGAffineTransformMakeScale(2.0, 2.0)
                    
                
                }else {
                
                    button.transform = CGAffineTransformMakeScale(0.3, 0.3)
                
                    
                
                }
                
                
                
            
            }
            
           
            }) { (Bool) -> Void in
                
                //实现跳转功能
                let publish = YDPublishViewController()
                
                let nv = UINavigationController(rootViewController: publish)
                
                
                self.viewController?.presentViewController(nv, animated: true, completion: { () -> Void in
                    
                    self.removeFromSuperview()
                    
                })
                
        }
        

    }
    
    //定义一个方法接收
    func receiveController (controller: UIViewController) {
    
        viewController = controller
        
        //将自己添加到控制器中
        
         viewController?.view.addSubview(self)
        
        self.snp_makeConstraints(closure: { (make) -> Void in
            
            make.edges.equalTo(viewController!.view.snp_edges)
            
            
        })
        
        

    }
    
    
    //创建一个类方法
    class func receiveVC (controller: UIViewController) {
        
        YDAddActionView().receiveController(controller)
        
        
        
    }
    
    //给btn加动画
    
    func addAnimation (btn: YDAddButton, time: CFTimeInterval, type: animationType) -> POPSpringAnimation{
        
        
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        
        if type == .UP {
            
            anim.toValue = NSValue(CGPoint: CGPointMake(btn.center.x, btn.center.y - screenHeight + 300))
            
        }else if type == .DOWN {
        
            anim.toValue = NSValue(CGPoint: CGPointMake(btn.center.x, btn.center.y + screenHeight))
        
        
        }
        
        anim.springBounciness = 14
        
        anim.springSpeed = 10
        
        
        //设置动画的开始时间
        anim.beginTime = time
        
        return anim
    
    }
    
    
    //显示动画
    
    func showAnimation () {
    
    
        for (key,button) in btnArr.enumerate() {

            
            let anim = addAnimation(button, time: CACurrentMediaTime() + 0.025 * Double(key), type: .UP)
        
            button.pop_addAnimation(anim, forKey: "center")
        
        
        }

    
    
    }
    
    //重写touch方法
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        //添加动画
        
        UIView.animateWithDuration(0.025 * 6.0, animations: { () -> Void in
            
            
            for (key,button) in self.btnArr.reverse().enumerate() {
                
                
                let anim = self.addAnimation(button, time: CACurrentMediaTime() + 0.025 * Double(key), type: .DOWN)
                
                button.pop_addAnimation(anim, forKey: "center")
                
                
            }
            
            
            }) { (_) -> Void in
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                    
                    //将本身从父控件删除
                    self.removeFromSuperview()
                    
                })
                
        }
    
    }
    
    
    
    //获取当前屏幕截图
    
    func getCurrentScreen() -> UIImage {
        
        // 1. 先要获取一下当前的window
        let window = UIApplication.sharedApplication().keyWindow!
        // 2. 开启绘图
        /*
        size: 大小
        opaque:是否透明
        scale: 缩放系数
        */
        UIGraphicsBeginImageContextWithOptions(kUIScreenSize, false, 1)
        
        // 3. 把window画在画板上
        window.drawViewHierarchyInRect(kUIScreenBounds, afterScreenUpdates: false)
        
        // 4. 拿到image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        // 5. 关闭画板
        UIGraphicsEndImageContext()
        
        return image
        
 
    
    }
    // 懒加载控件
    
    lazy var bjImageView: UIImageView = {
    
        let imgBJ = UIImageView()
        
        imgBJ.image = self.getCurrentScreen()

        
        let effect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        //创建一个毛玻璃效果
        
        let vImage = UIVisualEffectView(effect: effect)
        
        
        imgBJ.addSubview(vImage)
        
        //设置毛玻璃的约束
        
        vImage.snp_makeConstraints(closure: { (make) -> Void in
            
            make.edges.equalTo(imgBJ.snp_edges)
            
        })
        
    
        return imgBJ
        

    }()
    
    

}
